<?php
/**
 * 文章模块
 */
namespace App\Http\Controllers\Api;

use App\Http\Service\UserInstance;
use App\Models\Article;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ArticleController extends Controller
{
    /**
     * 列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $params = $request->all();

        $limit = isset($params['limit']) ? $params['limit'] : 10;

        $user = UserInstance::getInstance()->get();

        $list = Article::where(['user_id' => $user['id'], 'deleted_at' => null])->orderBy('id')->Paginate($limit);

        return $this->success("成功", $list);
    }

    /**
     * 新增
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        //
        $params = $request->all();

        $user = UserInstance::getInstance()->get();

        $params['user_id'] = $user['id'];

        $article           = Article::create($params);

        return $this->success("成功", $article);
    }

    /**
     * 详情
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        $user = UserInstance::getInstance()->get();

        $user_id = $user['id'];

        $article = Article::where(['user_id' => $user_id, 'id' => $id, 'deleted_at' => null])->first();

        if (!$article) {
            return $this->failed("找不到数据");
        }
        return $this->success("成功", $article);
    }

    /**
     * 全更新
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id)
    {
        $params  = $request->all();

        $user = UserInstance::getInstance()->get();

        $article = Article::where(['user_id' => $user['id'], 'id' => $id, 'deleted_at' => null])->first();
        if (!$article) {
            return $this->failed("找不到数据");
        }
        $article->content = $params['content'];
        $article->save();

        return $this->success("成功", $article);
    }

    /**
     * 删除
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        $user = UserInstance::getInstance()->get();

        $article = Article::where(['user_id' => $user['id'], 'id' => $id, 'deleted_at' => null])->first();

        if (!$article) {
            return $this->failed("找不到数据");
        }
        $article->deleted_at = date("Y-m-d H:i:s", time());

        $article->save();

        return $this->success("成功", $article);
    }
}
